﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

namespace Lost{
	/// <summary>
	/// 文本显示器，用于UI的Text动态文字显示
	/// </summary>
	[RequireComponent(typeof(Text))]
	public class TextShower : MonoBehaviour {
		///一秒钟显示多少个文字
		[SerializeField] float showSpeed = 60f;
		Text text;
		string content = "";
		int curIndex = 0;
		int len = 0;
		float timer = 0f;
		bool showEnd = false;
		void Start () {
			text = GetComponent<Text> ();
		}

		void Update () {
			if (showEnd) {
				return;
			}
			timer += Time.deltaTime;
			int nextIndex = (int)(timer * showSpeed);
			if (nextIndex > len) {
				nextIndex = len;
				showEnd = true;
			}
			while (curIndex < nextIndex) {
				text.text += content [curIndex++];
			}
		}

		///设置新内容，重新显示
		public void SetContent(string newContent){
			content = newContent;
			timer = 0f;
			len = content.Length;
			showEnd = false;
			curIndex = 0;
			text.text = "";
		}
		///显示所有文字
		public void ShowAll(){
			text.text = content;
			showEnd = true;
		}
	}
}
